package com.sky.handler;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.util.HashMap;

/**
 * @projectName: netty-cloud
 * @package: com.sky.handler
 * @className: MyMyAuthenticationFailureHandler
 * @author: zhl
 * @description: 实现本方法，替换security登录失败后自动跳转页面的处理方式
 * @date: 2024/4/25 11:42
 * @version: 1.0
 */
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    /**
     * Called when an authentication attempt fails.
     *
     * @param request   the request during which the authentication attempt occurred.
     * @param response  the response.
     * @param exception the exception which was thrown to reject the authentication
     *                  request.
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        HashMap<String,Object> hashMap = new HashMap<>(16);
        hashMap.put("code",400);
        hashMap.put("msg","failure");
        hashMap.put("data",exception.getMessage());
        String json = JSON.toJSONString(hashMap);

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);
    }
}
